import 'dart:async';
import 'package:flutter/material.dart';
import 'package:go_pong/route.dart';
import 'package:go_pong/utils/mixins/mixin_movements.dart';
import 'package:go_pong/views/home/home_view.dart';
import 'package:go_pong/views/play_area/sprites/ball.dart';
import 'package:go_pong/views/play_area/sprites/brick.dart';
import 'package:go_pong/widgets/stack_text.dart';

class PlayAreaView extends StatefulWidget {
  static const route = '/play_area';
  const PlayAreaView({Key? key}) : super(key: key);

  @override
  State<PlayAreaView> createState() => _PlayAreaViewState();
}

class _PlayAreaViewState extends State<PlayAreaView> with MixinMovements {
  void _gameEvent() {
    Timer.periodic(const Duration(milliseconds: 5), (timer) {
      ballTimer = timer;
      setState(() {
        updateDirection();
        moveBall();
        checkDeadBall();
        enemyMovement();
      });
    });
  }

  void _startGame() {
    if (!gameStart) {
      setState(() {
        gameStart = true;
        _gameEvent();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _startGame,
      onHorizontalDragUpdate: (DragUpdateDetails details) {
        if (gameStart) {
          double _position = details.delta.dx;
          if (_position > 0 && _position > 2.0) {
            setState(() {
              moveRight();
            });
          }
          if (_position < 0 && _position < -2.0) {
            setState(() {
              moveLeft();
            });
          }
        }
      },
      child: Scaffold(
        body: Center(
          child: Stack(
            children: [
              // if (dead)
              //   StackText(
              //     textSize: 25.0,
              //     xPosition: 0.0,
              //     yPosition: -0.5,
              //     text: '开始游戏',
              //     onTap: () => routePushReplaced(context, HomeView.route),
              //   ),
              if (!gameStart)
                const StackText(
                  textSize: 15.0,
                  xPosition: 0.0,
                  yPosition: 0.1,
                  text: '点击屏幕开始游戏',
                ),
              Brick(
                x: enemyX,
                isNegative: true,
                brickGlobalKey: botGlobalKey,
              ),
              Ball(
                x: ballX,
                y: ballY,
                ballGlobalKey: ballGlobalKey,
              ),
              Brick(
                x: playerX,
                isNegative: false,
                brickGlobalKey: playerGlobalKey,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
